﻿#region License

// Droid Manager - An Android Phone Tools Suite
// Copyright (C) 2011
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;
using DroidManager.Android;
using DroidManager.Data;
using DroidManager.Log;
using DroidManager.Plugins;
using DroidManager.UI;

namespace DroidManager
{
    internal static class Program
    {
        /// <summary>
        /// Logger
        /// </summary>
        private static Logger _log;

        /// <summary>
        /// Device Manager
        /// </summary>
        private static DeviceManager _dm;

        /// <summary>
        /// Plugin Engine
        /// </summary>
        private static PluginEngine _pe;

        /// <summary>
        /// Device Selection Dialog
        /// </summary>
        private static DeviceSelectionDialog _dsd;


        /// <summary>
        /// Punto di ingresso principale dell'applicazione.
        /// </summary>
        [STAThread]
        private static void Main(string[] parameters)
        {
            if (IsAlreadyRunning() && parameters.Length < 2)
            {
                MessageBox.Show("DroidManager is already running!", "Already running",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            CleanUpLogs();
            Initialize();
            _log.Info("App Started");

            if (parameters.Length >= 2)
            {
                ProcessParameters(parameters);
            }
            else
            {
                _log.Info("Loading Main Form");
                Application.Run(new Main());
            }
        }

        private static void CleanUpLogs()
        {
            if (Directory.Exists(GlobalVars.DmLogPath))
            {
                int i = 0;
                foreach (string file in Directory.GetFiles(GlobalVars.DmLogPath))
                {
                    i++;
                }
                if (i > 100)
                {
                    foreach (string file in Directory.GetFiles(GlobalVars.DmLogPath))
                    {
                        File.Delete(file);
                    }
                }
            }
        }

        private static bool IsAlreadyRunning()
        {
            int i = 0;
            foreach (Process process in Process.GetProcesses())
            {
                if (process.ProcessName == "DroidManager")
                {
                    i++;
                }
            }
            if (i > 1)
            {
                return true;
            }
            return false;
        }

        private static void Initialize()
        {
            GlobalVars.Initialize();
            _log = new Logger(GlobalVars.DmLogPath);
            _dm = DeviceManager.Instance;
            _pe = PluginEngine.Instance;
        }

        private static void ProcessParameters(string[] parameters)
        {
            string command = parameters[0];
            string path = parameters[1];

            if (command.ToLower() == "plugin")
            {
                _dsd = new DeviceSelectionDialog();
                if (System.IO.File.Exists(path))
                {
                    StartDll(path, parameters);
                    return;
                }
                else
                {
                    foreach (Plugin plugin in _pe.Plugins)
                    {
                        if (plugin.Name == path)
                        {
                            StartPlugin(plugin, PluginParameters(parameters));
                            return;
                        }
                    }
                }
            }
            MessageBox.Show("Wrong Parameters", "DroidManager", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            Environment.Exit(1);
        }

        private static void StartPlugin(Plugin plugin, string[] pluginparameters)
        {
            try
            {
                plugin.Threaded = false;
                if (_dm.Devices.Count != 1)
                {
                    _dsd.ShowDialog();
                    plugin.Start(_dsd.SelectedDevice, pluginparameters);
                }
                else
                {
                    plugin.Start(_dm.Devices[0], pluginparameters);
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                plugin.Start(null, pluginparameters);
            }
        }

        private static void StartDll(string path, string[] fullparameters)
        {
            Plugin plugin = new Plugin(path, false);
            if (plugin.Load())
            {
                if (_dm.Devices.Count != 1)
                {
                    _dsd.ShowDialog();
                    plugin.Start(_dsd.SelectedDevice, PluginParameters(fullparameters));   
                }
                else
                {
                    plugin.Start(_dm.Devices[0], PluginParameters(fullparameters));   
                }
            }
            else
            {
                MessageBox.Show("Unable to load plugin", "DroidManager - Error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                Environment.Exit(1);
            }
        }

        private static string[] PluginParameters(string[] fullparameters)
        {
            string[] pparameters = new string[fullparameters.Length - 2];
            for (int i = 2; i < fullparameters.Length; i++)
            {
                pparameters[i - 2] = fullparameters[i];
            }
            return pparameters;
        }
    }
}